using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Web;

namespace NorthwindWeb.Models
{ 
    public class TerritoryRepository : ITerritoryRepository
    {
        NorthwindEntities context = new NorthwindEntities();

        public IQueryable<Territory> All
        {
            get { return context.Territories; }
        }

        public IQueryable<Territory> AllIncluding(params Expression<Func<Territory, object>>[] includeProperties)
        {
            IQueryable<Territory> query = context.Territories;
            foreach (var includeProperty in includeProperties) {
                query = query.Include(includeProperty);
            }
            return query;
        }

        public Territory Find(string id)
        {
            return context.Territories.Single(x => x.TerritoryID == id);
        }

        public void InsertOrUpdate(Territory territory)
        {
            if (territory.TerritoryID == default(string)) {
                // New entity
                context.Territories.AddObject(territory);
            } else {
                // Existing entity
                context.Territories.Attach(territory);
                context.ObjectStateManager.ChangeObjectState(territory, EntityState.Modified);
            }
        }

        public void Delete(string id)
        {
            var territory = context.Territories.Single(x => x.TerritoryID == id);
            context.Territories.DeleteObject(territory);
        }

        public void Save()
        {
            context.SaveChanges();
        }
    }

    public interface ITerritoryRepository
    {
        IQueryable<Territory> All { get; }
        IQueryable<Territory> AllIncluding(params Expression<Func<Territory, object>>[] includeProperties);
        Territory Find(string id);
        void InsertOrUpdate(Territory territory);
        void Delete(string id);
        void Save();
    }
}